package com.chenglu.android.restaurant.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseMvpFragment;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.widget.UIndicator;
import com.chenglu.android.goodsinfo.GoodsInfoActivity;
import com.chenglu.android.goodsinfo.GoodsRestantInfoActivity;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.index.adapter.HomePicAdapter;
import com.chenglu.android.index.adapter.HomeTabTitleDataAdapter;
import com.chenglu.android.index.adapter.HomeTopicPagerAdapter;
import com.chenglu.android.index.bean.BannerBeanList;
import com.chenglu.android.index.bean.IndexRecomBean;
import com.chenglu.android.index.bean.PageListBean;
import com.chenglu.android.restaurant.RestaurantActivity;
import com.chenglu.android.restaurant.adapter.SearchShopAdapter;
import com.chenglu.android.restaurant.adapter.TopicCateAdapter;
import com.chenglu.android.restaurant.bean.RestaurantSearchBean;
import com.chenglu.android.restaurant.shop.details.ShopDetailsActivity;
import com.chenglu.android.supermarket.mvp.contract.SuperMarkerContract;
import com.chenglu.android.supermarket.mvp.presenter.SuperMarkerPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.relex.circleindicator.CircleIndicator;

/**
 * @author: lyj
 * @Created: by Copyright 2023/9/22 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：
 */
public class RestaurantHomeFragment extends BaseMvpFragment<SuperMarkerPresenter> implements SuperMarkerContract.View, TopicCateAdapter.OnItemClickListener {


    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_bgsearch)
    RelativeLayout llBgsearch;
    @BindView(R.id.rv_text_category)
    RecyclerView rvTextCategory;
    @BindView(R.id.rv_super_like)
    RecyclerView rvSuperLike;
    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.recommend_viewPager)
    ViewPager recommendViewPager;
    @BindView(R.id.indicator)
    CircleIndicator indicator;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.tv_free)
    TextView tvFree;
    @BindView(R.id.tv_discount)
    TextView tvDiscount;
    @BindView(R.id.tv_use_coupon)
    TextView tvUseCoupon;
    @BindView(R.id.ui_indicator2)
    UIndicator uiIndicator2;
    //分类的adapter
    private HomePicAdapter homePicAdapter;

    private static RestaurantActivity activity;

    private SearchShopAdapter searchShopAdapter;

    public static RestaurantHomeFragment newInstance(RestaurantActivity superMarkerActivity) {
        RestaurantHomeFragment fragment = new RestaurantHomeFragment();
        activity = superMarkerActivity;
        return fragment;
    }

    @Override
    protected int getLayoutId() {

        return R.layout.fragment_restaurant_home_market;
    }

    @Override
    protected void initView() {

        tvTitle.setText("餐饮");

        StatusBarUtil.immersive(getActivity());
        StatusBarUtil.setPaddingSmart(getActivity(), toolbar);

        mPresenter = new SuperMarkerPresenter();
        mPresenter.attachView(this);

//        initCategoryRv();

        initTitleDataAdapter();

        //初始化列表数据
        initShopRv();

        //图片分类
        mPresenter.getCategoryList(getMapdata());

        mPresenter.getSearchShop(setShopMap(Constant.zero, Constant.zero, Constant.zero, Constant.zero));

        //餐饮
//        mPresenter.getTabTitleData(setTabTitleMap(true, false, Constant.two));


    }


    List<IndexRecomBean.Data.Records> sellGoodsList = new ArrayList<>();


    //图片分类的集合
//    List<PageListBean.Data.Records> categoryList = new ArrayList<>();
//
//    private void initCategoryRv() {
//
//        homePicAdapter = new HomePicAdapter(mContext, categoryList);
//        //
//        rvHomeCategory.setLayoutManager(new GridLayoutManager(mContext, 4,
//                LinearLayoutManager.VERTICAL, false));
//
//        rvHomeCategory.setAdapter(homePicAdapter);
//
//        homePicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//            }
//        });
//    }

    List<IndexRecomBean.Data.Records> homeTitledataList = new ArrayList<>();
    private HomeTabTitleDataAdapter homeTabTitleDataAdapter;

    //推荐的商品列表 刷新和加载
    private void initTitleDataAdapter() {

        homeTabTitleDataAdapter = new HomeTabTitleDataAdapter(mContext, homeTitledataList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);

        rvSuperLike.setLayoutManager(gridLayoutManager);
        rvSuperLike.setAdapter(homeTabTitleDataAdapter);

        homeTabTitleDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });


    }


    //分类图片集合
    List<PageListBean.Data.Records> indexRecomList = new ArrayList<>();

    //分页的adapter
    private TopicCateAdapter menuAdapter;

    //推荐
    private void initTypeViewPager(int rowNum, int columnNum) {

        //1.根据数据的多少来分页，每页的数据为rw
        int singlePageDatasNum = rowNum * columnNum; //每个单页包含的数据量：2*4=8；
        int pageNum = indexRecomList.size() / singlePageDatasNum;//算出有几页菜单：20%8 = 3;
        if (indexRecomList.size() % singlePageDatasNum > 0) pageNum++;//如果取模大于0，就还要多一页出来，放剩下的不满项
        ArrayList<RecyclerView> mList = new ArrayList<>();
        for (int i = 0; i < pageNum; i++) {
            RecyclerView recyclerView = new RecyclerView(mContext);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, columnNum) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            recyclerView.setLayoutManager(gridLayoutManager);
            int fromIndex = i * singlePageDatasNum;
            int toIndex = (i + 1) * singlePageDatasNum;
            if (toIndex > indexRecomList.size()) toIndex = indexRecomList.size();
            //a.截取每个页面包含数据
            ArrayList<PageListBean.Data.Records> menuItems = new ArrayList<>(indexRecomList.subList(fromIndex, toIndex));
            //b.设置每个页面的适配器数据
            menuAdapter = new TopicCateAdapter(mContext, menuItems);
            menuAdapter.setOnItemClickListener(this);
            //c.绑定适配器，并添加到list
            recyclerView.setAdapter(menuAdapter);
            mList.add(recyclerView);
        }
        //2.ViewPager的适配器
        HomeTopicPagerAdapter menuViewPagerAdapter = new HomeTopicPagerAdapter(mList);
        recommendViewPager.setAdapter(menuViewPagerAdapter);
        //3.动态设置ViewPager的高度，并加载所有页面
        int height = Global.dp2px(80);//这里的80为MainMenuAdapter中布局文件高度
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                indexRecomList.size() <= columnNum ? height : height * rowNum);
        recommendViewPager.setLayoutParams(layoutParams);
        recommendViewPager.setOffscreenPageLimit(pageNum - 1);

        uiIndicator2.attachToViewPager(recommendViewPager);

    }


    @Override
    public void onTopicItemClick(PageListBean.Data.Records position, String categoryName, String id) {

    }

    List<RestaurantSearchBean.Data.Records> searchShopList = new ArrayList<>();

    private void initShopRv() {
//
        searchShopAdapter = new SearchShopAdapter(mContext, searchShopList);
        //
        rvSuperLike.setLayoutManager(new LinearLayoutManager(mContext));

        rvSuperLike.setAdapter(searchShopAdapter);

        searchShopAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case  R.id.rl_shop:
                        toRestaurantShop(mContext,searchShopList.get(position).getTenantId());
                        break;

                }
            }
        });
    }

    //跳转到商铺页面
    public static void toRestaurantShop(Context context, String tenantid) {
        Intent intent = new Intent(context, ShopDetailsActivity.class);
        intent.putExtra(ShopDetailsActivity.TENANTID, tenantid);
        context.startActivity(intent);

    }


    private Map<String, String> getMapdata() {
        Map<String, String> map = new HashMap<>();
        map.put("isIdxShow", Constant.one);
        map.put("level", Constant.two);
        map.put("pid", activity.getPid);
        map.put("shopsTypeId", Constant.two);

        return map;
    }

    private Map<String, String> setTabTitleMap(boolean istype, boolean isRecommendPlatform, String shopsId) {
        Map<String, String> map = new HashMap<>();
        if (istype) {
            map.put("shopsTypeId", shopsId);
        }
        if (isRecommendPlatform) {
            map.put("isRecommendPlatform", shopsId);
        }
        // 经纬度不授权 默认传0
        map.put("current", "1");
        map.put("size", Constant.SIZE + "");
        return map;
    }

    // {"params":{"current":"1","distanceAsc":"0","lng":"113.23172795283787",
    // "size":"50","saleDesc":"0","couponDesc":"0","scoreDesc":"0","lat":"23.187175666618707"}}
    private Map<String, String> setShopMap(String isScore, String isFree, String isDiscount, String isUseCoupon) {
        Map<String, String> map = new HashMap<>();
//        map.put("categoryId", activity.getPid);
        // 经纬度不授权 默认传0
        map.put("current", "1");
        //分类的id
//        map.put("categoryId", Constant.two);

        // 评分高低 值写死为0
        map.put("scoreDesc", isScore);
        // 是否免配送费 0-否 1-是
        map.put("postFeeFlag", isFree);
        //折扣商家 值写死为1
        map.put("distanceAsc", isDiscount);
        //可使用券 值写死为1 默认是0
        map.put("couponDesc", isUseCoupon);

        map.put("lat", "23.187175666618707");
        map.put("lng", "113.23172795283787");
//        map.put("shopsTypeId", Constant.two);
        map.put("size", 50 + "");
        return map;
    }


    //图片分类
    @Override
    public void getCategoryList(PageListBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            indexRecomList.add(bean.getData().getRecords().get(i));
        }
        initTypeViewPager(2, 4);
//        categoryList.notifyDataSetChanged();
    }


    @Override
    public void getBannerList(BannerBeanList bean) {

    }


    @Override
    public void getTabTitleData(IndexRecomBean bean) {

        if (bean.getData().getRecords().size() > 0) {
            for (int i = 0; i < bean.getData().getRecords().size(); i++) {
                homeTitledataList.add(bean.getData().getRecords().get(i));
            }

        }
        homeTabTitleDataAdapter.notifyDataSetChanged();
    }


    @Override
    public void getHotsellData(IndexRecomBean bean) {

    }


    //橙鹿优选列表搜索数据
    @Override
    public void getSearchShop(RestaurantSearchBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            searchShopList.add(bean.getData().getRecords().get(i));
        }
        searchShopAdapter.notifyDataSetChanged();
    }

    boolean isScore, isFree, isDiscount, isUseCoupon;
    String setScoreValue = "0";
    String setFreeValue = "0";
    String setDiscountValue = "0";
    String setUseCouponValue = "0";


    @OnClick({R.id.ll_bgsearch, R.id.tv_score, R.id.tv_free, R.id.tv_discount, R.id.tv_use_coupon, R.id.ll_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_bgsearch:
                mContext.startActivity(new Intent(getActivity(), GoodsInfoActivity.class));
                break;
            case R.id.tv_score:
                if (!isScore) {
                    isScore = true;
                    setPressColor(tvScore, R.color.all_black_text, R.drawable.corner_yellow_shape_4);

                    setScoreValue = "1";
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                } else {
                    isScore = false;
                    setPressColor(tvScore, R.color.color_999999, R.drawable.corner_white_shape_4);
                    setScoreValue = "0";
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                }

                break;
            case R.id.tv_free:
                if (!isFree) {
                    isFree = true;
                    setFreeValue = "1";
                    setPressColor(tvFree, R.color.all_black_text, R.drawable.corner_yellow_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                } else {
                    isFree = false;
                    setFreeValue = "0";
                    setPressColor(tvFree, R.color.color_999999, R.drawable.corner_white_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                }

                break;
            case R.id.tv_discount:
                if (!isDiscount) {
                    isDiscount = true;
                    setDiscountValue = "1";
                    setPressColor(tvDiscount, R.color.all_black_text, R.drawable.corner_yellow_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                } else {
                    isDiscount = false;
                    setDiscountValue = "0";
                    setPressColor(tvDiscount, R.color.color_999999, R.drawable.corner_white_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                }

                break;
            case R.id.tv_use_coupon:

                if (!isUseCoupon) {
                    isUseCoupon = true;
                    setUseCouponValue = "1";
                    setPressColor(tvUseCoupon, R.color.all_black_text, R.drawable.corner_yellow_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                } else {
                    isUseCoupon = false;
                    setUseCouponValue = "0";
                    setPressColor(tvUseCoupon, R.color.color_999999, R.drawable.corner_white_shape_4);
                    searchShopList.clear();
                    mPresenter.getSearchShop(setShopMap(setScoreValue, setFreeValue, setDiscountValue, setUseCouponValue));
                }
                break;
            case R.id.ll_back:
                getActivity().finish();
                break;
        }
    }

    //设置点击变换的颜色
    private void setPressColor(TextView textView, int p, int p2) {
        textView.setTextColor(ContextCompat.getColor(mContext, p));
        textView.setBackground(ContextCompat.getDrawable(mContext, p2));
    }
}
